import request from 'request-promise';
import { Router } from 'express';
import * as _ from "lodash";
import { createCipher } from 'crypto';
module.exports = app => {
    const config = app.libs.config;
    const db = app.db;
    const client = app.redis.client
    let orderManager = app.service.orderManager;
    
    app.post("/api/shop/saveOrder", async (req,res)=>{
        let user = req.user;
        let order = req.body;
        let is_pass = false;
        // if(req.body.postscript == "0"){
        //     is_pass = true;
        // }
        // if(!is_pass){
        //     let verifyCode = req.body.verifyCode
        //     let checkcodeinfo = await client.getAsync("pc_verify_code_"+req.body.mobile);
        //     if(!checkcodeinfo){
        //         res.json({status:"error",errorCode:"200003",messasge:"验证码已失效，请重新获取"})
        //         return ;
        //     }
        //     checkcodeinfo = JSON.parse(checkcodeinfo)
        //     if(checkcodeinfo.checkcode != verifyCode){
        //         res.json({status:"error",errorCode:"200003",messasge:"验证码错误，请重新获取"})
        //         return;
        //     }
        // }
        if(_.isInteger(order.total_price) && _.isInteger(order.goods_price) && _.isInteger(order.shipping_fee)){
            let result = await orderManager.saveOrder(order,user);
            res.json(result)
        }else{
            res.status(500).send("价格需格式化为整型，以分为单位");
        }
    });
    app.post("/api/shop/paycallback", async (req,res)=>{
        let data = req.body;
        let result = await orderManager.payCallBack(data);
        res.json(result);
        
    });
    app.get("/api/shop/getPayedOrder", async (req,res)=>{
        let user = req.user
        let result = await orderManager.getPayedOrderByUser(user.id);
        res.send(result)
    });
    app.post("/api/shop/saveProduct", async (req,res)=>{
        let products = require('../products.json')
        for(let product of products){
            await client.setAsync(`dj_product_${product.id}`,JSON.stringify(product));;
        }
        let result = await client.setAsync('dj_product_list',JSON.stringify(products));
        res.send(result);
    });
    app.get("/api/shop/getProducts", async (req,res)=>{
        let result = await client.getAsync('dj_product_list')
        res.json(JSON.parse(result));
    });
    app.get("/api/shop/getProduct", async (req,res)=>{
        let productid = req.query.productid;
        if(!!productid){
            let result = await client.getAsync(`dj_product_${productid}`)
            res.json(JSON.parse(result));
        }else{
            res.send("productid不能为空");
        }
        
    });
    app.post("/api/shop/pay/prepare", async (req,res)=>{
        let user = req.user;
        let saving = req.body;
        let passport = user.Passports;
        let pass = passport.filter((item)=>{
            return item.appid = config.paychannel.wechat.appid
        })
        let data  = {
            appid:config.paychannel.wechat.appid,
	        userKey: pass[0].identifier,
            merchantId:config.paychannel.wechat.channelNo,
            outTradeNo: saving.order_sn,
            "tradeType": "WX_JSAPI",
            "body": saving.description,
            "totalFee": saving.fee,
            "detail": saving.description,
            "attach": "no comment",
            "busCallback": config.paychannel.wechat.cburl
        }
        let options = {
            method: 'POST',
            uri: config.paychannel.wechat.payurl,
            body: data,
            json: true 
        };
        let result =  await request(options)
        res.json(result);
    });
}
